package org.freetek.linkdn.activity.login;

import org.freetek.linkdn.CommonBundleKeys;
import org.freetek.linkdn.LinkdnActivity;
import org.freetek.linkdn.R;
import org.freetek.linkdn.activity.home.HomeActivity;
import org.freetek.linkdn.util.StringUtil;
import org.freetek.linkdn.util.communication.LinkedInUpdatesWrapper;
import org.freetek.linkdn.util.model.LinkedInAuthResponse;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class LoginActivity extends LinkdnActivity {

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.login);

		final EditText etVerifier = (EditText) findViewById(R.id.Verifier);
		final Button btLogin = (Button) findViewById(R.id.Login);

		btLogin.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				final Editable eText = etVerifier.getText();
				if (null == eText) {
					return;
				}

				final String verifier = eText.toString();
				if (StringUtil.isNullOrEmpty(verifier)) {
					return;
				}

				persistVerifier();

				LinkedInAuthResponse authResponse = getAuthResponse();
				startActivityForResult(getHomeIntent(authResponse), RESULT_FIRST_USER);
			}

		});
	}

	private void persistVerifier() {
		// TODO store key in DB and skip login screen in the future
	}
	
	private String getVerifier() {
		// TODO this should read the verifier from DB
		final EditText etVerifier = (EditText) findViewById(R.id.Verifier);
		return etVerifier.getText().toString();
	}
	
	private Intent getHomeIntent(final LinkedInAuthResponse authResponce) {
		final Bundle extras = createAuthBundle();
		extras.putString(CommonBundleKeys.VERIFIER, getVerifier());
		
		final Intent homeIntent = new Intent(LoginActivity.this, HomeActivity.class);
		homeIntent.putExtras(extras);
		
		return homeIntent;
	}

}
